package zzps.exeed.web.servlet;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import zzps.exeed.web.Context;
import zzps.exeed.web.http.HttpMethod;
import zzps.exeed.web.transformer.InputOutputTransformerManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class ExeedServletContext implements Context {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private URL url;
    private URI uri;
    private String path;
    private HttpMethod httpMethod;

    public ExeedServletContext(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        try {
            url = new URL(request.getRequestURL().toString());
            uri = url.toURI();
        } catch (MalformedURLException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
        path = url.getPath();
        httpMethod = HttpMethod.resolve(request.getMethod());
        try {
            request.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public HttpServletRequest request(){
        return request;
    }
    @Override
    public HttpServletResponse response(){
        return response;
    }

    @Override
    public String path() {
        return path;
    }

    @Override
    public URL url() {
        return url;
    }

    @Override
    public URI uri() {
        return uri;
    }

    public HttpMethod method(){
        return httpMethod;
    }

    @Override
    public String getParameter(String name) {
        return request.getParameter(name);
    }

    @Override
    public InputStream getInputStream() {
        try {
            return request.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getContentType() {
        return request.getContentType();
    }

    @Override
    public OutputStream getOutputStream() {
        try {
            return response.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void status(int status) {
        response.setStatus(status);
    }

    @Override
    public void setContentType(String type) {
        response.setContentType(type);
    }
}
